package com.dqhl.community.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.dqhl.community.R;
import com.dqhl.community.adapter.RepariRecordListAdapter;
import com.dqhl.community.base.BaseFragment;
import com.dqhl.community.model.RepairRecord;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.JsonUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * description: 报修已解决
 * autour: guanluocang
 * date: 2016/11/16 14:04
 */
public class RepairRecordUnfinishFragment extends BaseFragment implements View.OnClickListener {

    private ListView unfinish_Listview;
    Handler handler = new Handler();
    private TextView tvNoInfo;
    private RepariRecordListAdapter repariAdapter;
    private List<RepairRecord> repariRecordList = new ArrayList<>();
    private List<RepairRecord> moreRecordList = new ArrayList<>();
    private PtrClassicFrameLayout ptrClassicFrameLayout;
    private int page = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_repair_record_unfinish, container, false);
        initView(view);
        initData();
        return view;
    }

    private void initView(View view) {
        unfinish_Listview = (ListView) view.findViewById(R.id.unfinish_Listview);
        ptrClassicFrameLayout = (PtrClassicFrameLayout) view.findViewById(R.id.ptr_list);
        tvNoInfo = (TextView) view.findViewById(R.id.tv_no_info);
    }

    private void initData() {
        //下拉刷新
        ptrClassicFrameLayout.postDelayed(new Runnable() {

            @Override
            public void run() {
                ptrClassicFrameLayout.autoRefresh(true);
                ptrClassicFrameLayout.setLoadMoreEnable(true);
            }
        }, 150);

        ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ptrClassicFrameLayout.refreshComplete();
                        page = 1;
                        //获取数据
                        getData();
                        ptrClassicFrameLayout.setLoadMoreEnable(true);
                    }
                }, 1000);
            }
        });

        ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void loadMore() {
                handler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        ptrClassicFrameLayout.loadMoreComplete(true);
                        page++;
                        Dlog.e("GGGpage " + page);
                        loadMorData();
                    }
                }, 1000);
            }
        });
    }

    //请求数据
    public void getData() {
        showCustomLoadBar(".");
        RequestParams params = new RequestParams(Config.Api.repair_record);
        params.addBodyParameter("userid", spUserInfo.getString(Constant.USERID, ""));
        params.addBodyParameter("state", "1");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("GG保修记录返回结果" + result);
                int errcode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getInfo(result, "errMsg");
                String data = JsonUtils.getInfo(result, "data");

                if (errcode == 0) {
                    repariRecordList = parseData(data);
                    Dlog.e("GG报修返回data" + repariRecordList);
                    if (repariRecordList.size() <= 0) {
                        tvNoInfo.setVisibility(View.VISIBLE);
                        ptrClassicFrameLayout.setVisibility(View.GONE);
                        unfinish_Listview.setVisibility(View.GONE);
                    }
                    repariAdapter = new RepariRecordListAdapter(
                            getActivity(), repariRecordList, new RepariRecordListAdapter.onCompleteListener() {
                        @Override
                        public void onComplete(int position) {
                            Dlog.e(" GGGG  "+repariRecordList.get(position).getId());
                            doComplete(repariRecordList.get(position).getId());
                        }
                    }, new RepariRecordListAdapter.onCancleListener() {
                        @Override
                        public void onCancle(int position) {
                            doCancle(repariRecordList.get(position).getId());
                        }
                    });
                    unfinish_Listview.setAdapter(repariAdapter);
                } else {
                    tvNoInfo.setVisibility(View.VISIBLE);
                    ptrClassicFrameLayout.setVisibility(View.GONE);
                    unfinish_Listview.setVisibility(View.GONE);
                }
//                hideCustomLoadBar();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
//                hideCustomLoadBar();
                Dlog.e(ex + "GG保修记录返回结果" + isOnCallback);
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Dlog.e("GG保修记录返回结果onCancelled");
            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    private List<RepairRecord> parseData(String str) {
        List<RepairRecord> data = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(str);
            RepairRecord model;
            for (int i = 0; i < array.length(); i++) {
                JSONObject object = array.getJSONObject(i);
                model = new RepairRecord();
                model.setId(object.getString("id"));
                model.setStatus(object.getString("status"));
                model.setCommunity_id(object.getString("community_id"));
                model.setBuilding_id(object.getString("building_id"));
                model.setUnit_id(object.getString("unit_id"));
                model.setResidence_id(object.getString("residence_id"));
                model.setName(object.getString("name"));
                model.setTelephone(object.getString("telephone"));
                model.setContent_id(object.getString("content_id"));
                model.setAdd_time(object.getString("add_time"));
                model.setContent(object.getString("content"));
                model.setPic_a(object.getString("pic_a"));
                model.setPic_b(object.getString("pic_b"));
                model.setPic_c(object.getString("pic_c"));
                model.setPic_d(object.getString("pic_d"));
                data.add(model);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return data;
    }

    //加载更多
    public void loadMorData() {
        showCustomLoadBar(".");
        RequestParams params = new RequestParams(Config.Api.repair_record);
        params.addBodyParameter("userid", spUserInfo.getString(Constant.USERID, ""));
        params.addBodyParameter("state", "1");
        params.addBodyParameter("page", page + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("GG上提返回结果" + result);
                int errcode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getInfo(result, "errMsg");
                String data = JsonUtils.getInfo(result, "data");

                if (errcode == 0) {
                    moreRecordList = parseData(data);
                    repariRecordList.addAll(moreRecordList);
                    repariAdapter.notifyDataSetChanged();
                } else {
                    page = page;
                    toast("没有更多");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    @Override
    public void onClick(View view) {

    }

    //报修确认
    public void doComplete(String orderId){
        Dlog.e("GGdoComplete"+orderId);
        RequestParams params = new RequestParams(Config.Api.repairReceipt);
        params.addBodyParameter("order_id",orderId);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                if(errCode == 0){
                    toast(errMsg);
                    initData();
                }else {
                    toast(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //取消
    public void doCancle(String orderId){
        Dlog.e("GGdoCancle"+orderId);
        RequestParams params = new RequestParams(Config.Api.repairCancel);
        params.addBodyParameter("order_id",orderId);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                if(errCode == 0){
                    toast(errMsg);
                    initData();
                }else {
                    toast(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
